#include "LOS.h"

using namespace Method;

LOS::LOS(shared_ptr<const Matrix> SLAEMatrix, shared_ptr<const Matrix> Preconditioner,
	shared_ptr<const Vector> RightPart, shared_ptr<const Vector> Approximation)
{
	_matrix = SLAEMatrix;
	_preconditioner = Preconditioner;
	_rightPart = RightPart;
	_approximation = Approximation;

	p.resize(RightPart->size());
	r.resize(RightPart->size());
	A_r.resize(RightPart->size());
	z.resize(RightPart->size());

	if (Approximation != nullptr)
		_result = shared_ptr<Vector>(new Vector(*Approximation));
	else _result = shared_ptr<Vector>(new Vector(_rightPart->size()));

	_matrix->MultMatrixVector(*_result, r);
	r = *(const_cast<Vector *>(&(*_rightPart))) - r;
	_matrix->MultMatrixVector(r, p);
	z = r;
	_residual = 0;
}

LOS::~LOS()
{

}


void LOS::nextIteration()
{
	alpha = p * r / (p * p);
	*_result += z * alpha;
	r = r - p * alpha;
	_matrix->MultMatrixVector(r, A_r);
	betta = p * r / (p * p);
	z = r + z * betta;
	p = A_r + p * betta;
	r = r;
	_residual = sqrt(r * r);
}
